import router from "@/router"
import useUserStore from "@/store/modules/user"
import setting from "./setting"
import nprogress from "nprogress"
import "nprogress/nprogress.css"

router.beforeEach(async (to, _, next) => {
    nprogress.start()
    document.title = to.meta.title + `| ${setting.title}`
    const userStore = useUserStore()
    if (!userStore.token) {
        // 无 token
        if (to.path === "/login") {
            next()
        } else {
            next({ path: "/login", query: { redirect: to.path } })
        }
    } else {
        // 有 token
        // 有 token 无 userinfo 则获取 userinfo，如获取失败则退出登录
        if (!userStore.username) {
            try {
                await userStore.userInfo()
            } catch (error) {
                await userStore.userLogout()
                next({ path: "/login", query: { redirect: to.path } })
            }
        }

        if (to.path === "/login") {
            next({ path: "/" })
        } else {
            next()
        }
    }

    // try {
    //     // 没有 username 去获取用户信息
    //     await userStore.userInfo()
    //     next()
    // } catch (error) {
    //     await userStore.userLogout()
    //     next({ path: "/login", query: { redirect: to.path } })
    // }
})

router.afterEach(() => {
    nprogress.done()
})
